package web.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.LyyBaseResponse;
import domain.ProfilePhoto;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.ProfilePhotoService;
import service.UserService;
import service.impl.ProfilePhotoServiceImpl;
import service.impl.UserServiceImpl;
import utils.LyyLogUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@WebServlet("/updateUserInfo")
public class UpdateUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        User user=new User();
        Map<String, String[]> parameterMap = request.getParameterMap();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        LyyLogUtil.logD("前端上送的user为："+user);

        String userId = request.getParameter("userId");
        LyyLogUtil.logD("前端送的userId："+userId);
        String pictureStr = request.getParameter("pictureStr");
        LyyLogUtil.logD("前端送的pictureStr："+pictureStr);
        ProfilePhotoService service=new ProfilePhotoServiceImpl();
        ProfilePhoto profilePhoto = new ProfilePhoto();
        profilePhoto.setUploadTime(new Date());
        profilePhoto.setPictureStr(pictureStr);

        UserService userService=new UserServiceImpl();
        Exception exception=null;
        try {
            profilePhoto.setUserId(Integer.parseInt(userId));
        } catch (NumberFormatException e) {
            exception=e;
            e.printStackTrace();
        }
        boolean b=false;
        boolean b2=false;
        try {
             b = userService.updateUserInfo(user);
             b2 = service.addPhoto(profilePhoto);
        } catch (Exception e) {
            e.printStackTrace();
            exception=e;
        }
        LyyBaseResponse lyyBaseResponse=new LyyBaseResponse();
        if(exception!=null||!b||!b2){
            lyyBaseResponse.setStatus(0);
            if(exception!=null){
                lyyBaseResponse.setErrMsg("更新信息失败："+exception.getMessage());
            }else {
                lyyBaseResponse.setErrMsg("更新信息失败!");
            }
        }
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(response.getOutputStream(),lyyBaseResponse);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
